package com.ComputerSales.controller;


import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import com.ComputerSales.entity.OrderDetail;
import com.ComputerSales.entity.Orders;
import com.ComputerSales.entity.Product;
import com.ComputerSales.service.IOrderDetailService;
import com.ComputerSales.service.IOrdersService;
import com.ComputerSales.service.IProductService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import freemarker.cache.StrongCacheStorage;
import org.assertj.core.error.uri.ShouldHaveUserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 作者
 * @since 2024-06-26
 */
@Controller
@RequestMapping("/orders")
public class OrdersController {

    @Autowired
    private IOrdersService ordersService;

    @Autowired
    private IOrderDetailService orderDetailService;

    @Autowired
    private IProductService productService;

    @PostMapping
    @ResponseBody
    public SaResult addOrder(@RequestParam Integer productId) {
//        商品信息
        Product product = productService.getById(productId);
        if (product.getStock() == 0) {
            return SaResult.error("商品缺货");
        } else {
            Orders orders = new Orders();
            orders.setUserId(StpUtil.getLoginIdAsInt());
            orders.setOrderDate(LocalDateTime.now());
            orders.setTotalAmount(product.getPrice());

            ordersService.save(orders);

//        订单详情
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setOrderId(orders.getId());
            orderDetail.setProductId(productId);
            orderDetail.setQuantity(1);
            orderDetail.setSubPrice(product.getPrice());
            orderDetailService.save(orderDetail);

//        更新商品库存
            product.setStock(product.getStock()-1);
            productService.updateById(product);
            return SaResult.ok();
        }

    }

    @GetMapping("/me")
    public String myOrder(Model model) {
        List<Orders> ordersList = ordersService.list(new QueryWrapper<Orders>()
                .eq("user_id", StpUtil.getLoginIdAsInt()));
        model.addAttribute("orders", ordersList);
        return "user/order";
    }

    @GetMapping
    public String allOrder(Model model) {
        List<Orders> ordersList = ordersService.list();
        model.addAttribute("orders", ordersList);
        return "admin/order";
    }

}
